<?php
session_start();

$result = [
    'status' => 0,
    'data' => null,
    'message' => '未知错误'
];

include_once '../mysql/connect_mysql.php';
include_once '../mysql/is-mysql.php';

if (isset($_SESSION['userid'])) {
    if (isset($is_mysql) && $is_mysql) {
        $user = $_SESSION['userid'];
        $balance = isset($_GET['balance']) ? $_GET['balance'] : false;

        $total_income = getTotalIncome($mysql, $user)[0]['totalincome'];
        $total_expend = getTotalExpend($mysql, $user)[0]['totalincome'];
        $baseMoney = getBaseMoney($mysql, $user)[0]['basemoney'];
        

        if ($balance === false) {
            // 获取余额
            $total_income = $total_income + $baseMoney;
            $result['status'] = 1;
            $balance = round($total_income - $total_expend, 2);
            $result['data'] = $balance == 0 ? '0.00' : $balance;
            $result['message'] = '获取数据成功';
            
        }
        else {
            // 设置基础金额
           $bmoney = $balance + $total_expend - $total_income;
           if (setBaseMoney($mysql, $user, $bmoney)) {
               $result['status'] = 1;
               $result['message'] = '设置成功';
           }
           else {
               $result['status'] = 0;
               $result['message'] = '设置失败';
           };
        };
    }
    else {
        $result['message'] = '数据库连接错误';
    };
}
else {
    $result['message'] = '用户未登入';
};

echo json_encode($result);

// 获取基础金额
function getBaseMoney(&$mysql, $user) {
$select = <<< EOT
select basemoney
from users
where id='{$user}'
EOT;

    return isMysql($select, $mysql);
};

// 设置基础金额
function setBaseMoney(&$mysql, $user, $bmoney) {
$update = <<< EOT
update users
set basemoney={$bmoney}
where id='{$user}'
EOT;

    return isMysql($update, $mysql);
};
// 获取总支出
function getTotalExpend(&$mysql, $user) {
$select = <<< EOT
select sum(money) as 'totalincome'
from incspes i inner join types t
on i.user='{$user}' and i.type=t.typecode and t.incspe=-1
EOT;

    return isMysql($select, $mysql);
};

// 获取总收入
function getTotalIncome(&$mysql, $user) {
$select = <<< EOT
select sum(money) as 'totalincome'
from incspes i inner join types t
on i.user='{$user}' and i.type=t.typecode and t.incspe=1
EOT;

    return isMysql($select, $mysql);
};
?>